package com.xhy.documents_collection.entity.PO.task;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.xhy.documents_collection.scheduler.SchedulerData;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 
 * </p>
 *
 * @author xhy
 * @since 2023-03-03
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class TaskTimingRecord implements Serializable, Delayed,SchedulerData {

    public TaskTimingRecord(Integer id){
        this.id = id;
    }
    public TaskTimingRecord(){

    }

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @NotNull(message = "请选择定时的任务")
    private Integer taskId;

    // 创建任务后任务名不可改变,因此冗余字段
    private String taskName;

    private Integer userId;

    private String subject;

    private String content;

    private Long fileSize;

    @Email(message = "邮箱不合法")
    private String receive;

    @NotNull(message = "请设置发送日期")
    private Date sendTime;

    /**
     * 状态。0进行中,1发送成功,2发送失败
     */
    private Integer state;

    @NotNull(message = "邮件方式不可为空")
    private Integer way;

    @TableField(exist = false)
    private String stateName;

    @TableField(exist = false)
    long expire; // 过期时间 = 定时发送时间 - 当前时间  sendTime - nowDay

    private Boolean isDeleted;

    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreated;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModify;
    public void setExpire(){
        // 过期时间 = 截止时间
        this.expire = this.sendTime.getTime();
    }



    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        long f = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        return (int) f;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TaskTimingRecord that = (TaskTimingRecord) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }


}
